import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:my_app/app/core/theme/app_colors.dart';
import 'package:my_app/app/widgets/custom_image_widget.dart';
import 'package:my_app/app/widgets/dialog/custom_confirm_dialog_widget.dart';
import 'package:my_app/app/widgets/image_preview_gallery_widget.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

/// custom_image_picker_widget.dart
///
/// Created by fuchuanwei on Fri Mar 24 2023.
///
/// Description: 自定义图片选择器
///    flutter_smart_dialog、wechat_assets_picker、wechat_camera_picker
///
class CustomImagePickerWidget extends StatefulWidget {
  ///图片选择器高度
  final double height;

  ///图片选择器宽度
  final double width;

  ///图片最大数量
  final int maxCount;

  ///图片地址列表
  final List<ImageGalleryEntity>? imageEntitys;

  ///是否允许拍照
  final bool isCamera;

  ///是否仅允许拍照
  final bool isOnlyCamera;

  ///是否开启多选
  final bool isMultiple;

  ///请求类型默认为图片
  final RequestType requestType;

  ///设置圆角
  final double? radius;

  ///是否开启预览
  final bool? isPreview;

  final CustomImagePickerWidgetController? controller;

  ///每个图片的间隔
  final double? spacing;

  ///每行图片的间隔
  final double? runSpacing;

  const CustomImagePickerWidget({
    super.key,
    this.height = 80.0,
    this.width = 80.0,
    this.maxCount = 9,
    this.imageEntitys,
    this.isCamera = true,
    this.isMultiple = true,
    this.requestType = RequestType.image,
    this.radius,
    this.isOnlyCamera = false,
    this.controller,
    this.isPreview,
    this.spacing,
    this.runSpacing,
  });

  @override
  State<CustomImagePickerWidget> createState() =>
      _CustomImagePickerWidgetState();
}

class _CustomImagePickerWidgetState extends State<CustomImagePickerWidget> {
  ///选中的资源列表
  List<AssetEntity> selectedAssets = [];

  ///初始化图片列表
  List<ImageGalleryEntity> imageEntitys = [];

  ///获取允许可选最大的资源数量
  int get maxAssets => widget.maxCount - imageEntitys.length;

  ///所有图片列表
  List<ImageGalleryEntity> images = [];

  @override
  void initState() {
    imageEntitys = widget.imageEntitys ?? [];
    super.initState();
    widget.controller?.state = this;
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isOnlyCamera == true && widget.isCamera == false) {
      throw ArgumentError("参数异常:isOnlyCamera为true时,isCamera不能为false");
    }
    return Wrap(
      spacing: widget.spacing ?? 10.0,
      runSpacing: widget.runSpacing ?? 10.0,
      children: [
        for (int i = 0; i < imageEntitys.length; i++)
          buildUrlsWidgetItem(
            imageEntitys[i],
            curIndex: i,
          ),
        for (int i = 0; i < selectedAssets.length; i++)
          buildAssetEntityWidgetItem(
            selectedAssets[i],
            curIndex: i,
          ),
        buildImagePicker(),
      ],
    );
  }

  Widget buildUrlsWidgetItem(ImageGalleryEntity entity, {int? curIndex}) {
    return buildImageItem(
      onRemove: (value) {
        if (value) {
          setState(() {
            imageEntitys.remove(entity);
          });
        }
      },
      onTap: () {
        previewImages(
          index: curIndex ?? 0,
        );
      },
      child: CustomImageWidget(
        tag: entity.tag,
        width: widget.width,
        height: widget.height,
        imageUrl: entity.url!,
        radius: widget.radius ?? 5.0,
        isPreview: false,
      ),
    );
  }

  void previewImages({required int index}) async {
    await getAllImageEntitys();
    Get.to(
      () => PhotoPreviewGalleryWidget(
        images: images,
        index: index,
      ),
    );
  }

  Widget buildAssetEntityWidgetItem(AssetEntity entity, {int curIndex = 0}) {
    return buildImageItem(
      onRemove: (value) {
        if (value) {
          setState(() {
            selectedAssets.remove(entity);
          });
        }
      },
      onTap: () {
        int index =
            imageEntitys.isEmpty ? curIndex : imageEntitys.length + curIndex;
        previewImages(index: index);
      },
      child: Hero(
        tag: entity.id,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(widget.radius ?? 5.0),
          child: AssetEntityImage(
            entity,
            isOriginal: false,
            width: widget.width,
            height: widget.height,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  Widget buildImageItem({
    required Widget child,
    Function? onRemove,
    Function? onTap,
  }) {
    return Stack(
      children: [
        GestureDetector(
          onTap: () => onTap!(),
          child: child,
        ),
        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            onTap: () async {
              bool result = await showRemoveImageConfirmDialog();
              onRemove!(result);
            },
            child: Container(
              width: widget.width * 0.25,
              height: widget.width * 0.25,
              alignment: Alignment.topRight,
              decoration: BoxDecoration(
                color: Color(0xFF373737),
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(widget.radius ?? 5.0),
                  bottomLeft: Radius.circular(widget.width * 0.25),
                ),
              ),
              child: Icon(
                Icons.close,
                color: Colors.white,
                size: widget.width * 0.17,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildImagePicker() {
    ///此处 使用 Ink 存在bug
    return GestureDetector(
      onTap: () => widget.isCamera
          ? widget.isOnlyCamera
              ? chooseImageByCamera()
              : showImagePickerTypeDialog()
          : chooseImageByGallery(),
      child: Container(
        width: widget.width,
        height: widget.height,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(widget.radius ?? 5.0),
          color: Color(0xFFf4f5f7),
        ),
        child: Icon(
          Icons.camera_alt_rounded,
          color: Color(0xFFd3d4d6),
        ),
      ),
    );
  }

  AssetPickerConfig get assetPickerConfig => AssetPickerConfig(
        selectedAssets: selectedAssets,
        maxAssets: widget.isMultiple ? maxAssets : 1,
        requestType: widget.requestType,
        specialPickerType:
            widget.isMultiple ? SpecialPickerType.noPreview : null,
      );

  Future chooseImageByGallery() async {
    List<AssetEntity> entities = await AssetPicker.pickAssets(
          context,
          pickerConfig: assetPickerConfig,
        ) ??
        [];
    setState(() {
      selectedAssets = entities;
    });
  }

  ///获取选择的文件地址
  Future<List<ImageGalleryEntity>> getSelectedAssetsImageGalleryEntity() async {
    if (selectedAssets.isEmpty) return [];
    List<ImageGalleryEntity> entitys = [];
    for (var asset in selectedAssets) {
      String? path = (await asset.file)?.path;
      if (path != null) {
        entitys.add(ImageGalleryEntity(
          url: path,
          tag: asset.id,
        ));
      }
    }
    return entitys;
  }

  ///获取选择的文件
  Future<List<File>> getSelectedAssetsFile() async {
    if (selectedAssets.isEmpty) return [];
    List<File> files = [];
    for (var asset in selectedAssets) {
      File? file = await asset.file;
      print("${file!.lengthSync() / 1024 / 1024}MB");
      files.add(file);
    }
    return files;
  }

  ///获取所有图片实体
  Future getAllImageEntitys() async {
    List<ImageGalleryEntity> pathList =
        await getSelectedAssetsImageGalleryEntity();
    setState(() {
      images = [...imageEntitys, ...pathList];
    });
  }

  ///通过相机选择图片
  Future chooseImageByCamera() async {
    if (maxAssets == selectedAssets.length) {
      SmartDialog.showNotify(msg: "所选图片数量已达上限", notifyType: NotifyType.warning);
      return;
    }
    final AssetEntity? entity = await CameraPicker.pickFromCamera(
      context,
      pickerConfig: const CameraPickerConfig(),
    );
    if (entity != null) {
      setState(() {
        selectedAssets.add(entity);
      });
    }
  }

  void clear() {
    setState(() {
      imageEntitys.clear();
      selectedAssets.clear();
      images.clear();
    });
  }

  Future<bool> showRemoveImageConfirmDialog() async {
    bool result = false;
    await SmartDialog.show(
      tag: "ImageRemoveDialog",
      builder: (ctx) => CustomConfirmDialogWidget(
        onConfirm: () {
          SmartDialog.dismiss(tag: "ImageRemoveDialog");
          result = true;
        },
        onCancel: () {
          SmartDialog.dismiss(tag: "ImageRemoveDialog");
          result = false;
        },
      ),
    );
    return result;
  }

  void showImagePickerTypeDialog() {
    SmartDialog.show(
      tag: "ImageTypeDialog",
      alignment: Alignment.bottomCenter,
      builder: (ctx) => Container(
        height: 100,
        width: double.infinity,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5.0),
            topRight: Radius.circular(5.0),
          ),
        ),
        child: Column(
          children: [
            TextButton(
                onPressed: () => {
                      SmartDialog.dismiss(tag: "ImageTypeDialog"),
                      chooseImageByCamera()
                    },
                child: Text('拍摄')),
            Divider(
              height: 2,
              color: dividerColor,
              thickness: 1,
            ),
            TextButton(
                onPressed: () => {
                      SmartDialog.dismiss(tag: "ImageTypeDialog"),
                      chooseImageByGallery()
                    },
                child: Text('从相册选择'))
          ],
        ),
      ),
    );
  }
}

class CustomImagePickerWidgetController {
  // ignore: library_private_types_in_public_api
  _CustomImagePickerWidgetState? customAssetsPickerWidgetState;

  // ignore: library_private_types_in_public_api
  set state(_CustomImagePickerWidgetState state) {
    customAssetsPickerWidgetState = state;
  }

  ///清空所有图片
  void clear() {
    customAssetsPickerWidgetState!.clear();
  }

  ///获取选择的图片文件列表
  Future<List<List>> getSelectedImages() async {
    List<List> result = [];
    var files = await customAssetsPickerWidgetState!.getSelectedAssetsFile();
    var imageEntity = customAssetsPickerWidgetState!.imageEntitys;
    if (imageEntity.isNotEmpty) {
      result.add(imageEntity);
    }
    if (files.isNotEmpty) {
      result.add([]);
      result.add(files);
    }
    return result;
  }
}
